package com.szh.gulimall.product.service.impl;

import com.szh.gulimall.product.entity.SkuImagesEntity;
import com.szh.gulimall.product.entity.SpuInfoDescEntity;
import com.szh.gulimall.product.service.*;
import com.szh.gulimall.product.vo.SkuItemSaleAttrVo;
import com.szh.gulimall.product.vo.SkuItemVo;
import com.szh.gulimall.product.vo.SpuItemAttrGroupVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szh.common.utils.PageUtils;
import com.szh.common.utils.Query;
import com.szh.gulimall.product.dao.SkuInfoDao;
import com.szh.gulimall.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;

@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<>()
        );
        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(List<SkuInfoEntity> skuInfoEntityList) {
        this.saveBatch(skuInfoEntityList);
    }

    /**
     * 条件查询sku列表
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(obj -> obj.eq("sku_id", key).or().like("sku_name", key));
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            queryWrapper.ge("price", min);
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)) {
            BigDecimal bigDecimal = new BigDecimal(max);
            if (bigDecimal.compareTo(new BigDecimal("0")) > 0) {
                queryWrapper.le("price", max);
            }
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    /**
     * 查询当前spuId对应的所有sku信息
     */
    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_id", spuId);
        List<SkuInfoEntity> skuList = this.list(queryWrapper);
        return skuList;
    }

    /**
     * 详情页：展示当前sku的详细信息
     */
    @Override
    public SkuItemVo findSkuItemDetail(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();
        CompletableFuture<SkuInfoEntity> skuInfoEntityFuture = CompletableFuture.supplyAsync(() -> {
            //1.sku基本信息 pms_sku_info
            SkuInfoEntity skuInfoEntity = this.getById(skuId);
            skuItemVo.setSkuInfoEntity(skuInfoEntity);
            return skuInfoEntity;
        }, threadPoolExecutor);
        //任务2、3、4需要用到spuId、catalogId，所以要等待任务1完成才可以继续执行
        CompletableFuture<Void> skuItemSaleAttrFuture = skuInfoEntityFuture.thenAcceptAsync(res -> {
            //2.spu的销售属性组合信息
            Long spuId = res.getSpuId();
            List<SkuItemSaleAttrVo> skuItemSaleAttrList = skuSaleAttrValueService.getSaleAttrsBySpuId(spuId);
            skuItemVo.setSkuItemSaleAttrList(skuItemSaleAttrList);
        }, threadPoolExecutor);
        CompletableFuture<Void> spuInfoDescFuture = skuInfoEntityFuture.thenAcceptAsync(res -> {
            //3.spu的基本信息 pms_spu_info_desc
            Long spuId = res.getSpuId();
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(spuId);
            skuItemVo.setSpuInfoDescEntity(spuInfoDescEntity);
        }, threadPoolExecutor);
        CompletableFuture<Void> spuItemAttrGroupFuture = skuInfoEntityFuture.thenAcceptAsync(res -> {
            //4.spu的规格参数信息
            Long spuId = res.getSpuId();
            Long catalogId = res.getCatalogId();
            List<SpuItemAttrGroupVo> spuItemAttrGroupList = attrGroupService.getAttrGroupWithAttrsBySpuId(spuId, catalogId);
            skuItemVo.setSpuItemAttrGroupList(spuItemAttrGroupList);
        }, threadPoolExecutor);
        //任务5无需依赖上面几个任务的执行、结果，所以可以单独开一个异步线程执行
        CompletableFuture<Void> skuImagesEntityFuture = CompletableFuture.runAsync(() -> {
            //5.sku图片信息 pms_sku_images
            List<SkuImagesEntity> skuImagesEntityList = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setSkuImagesEntityList(skuImagesEntityList);
        }, threadPoolExecutor);
        //等待任务1到任务5全部完成之后，才可以返回最终的数据
        CompletableFuture.allOf(skuInfoEntityFuture, skuItemSaleAttrFuture, spuInfoDescFuture, spuItemAttrGroupFuture, skuImagesEntityFuture).get();
        return skuItemVo;
    }

}